<?php


namespace Xtsb\Cims\Ocr\Invoice;

use Xtsb\Cims\File\File;
use app\Http\Finance\Servers\FinanceCostInvoiceServer;
use app\Http\Finance\Servers\FinanceInvoicePageServer;
use SimpleXMLElement;
use think\facade\Db;

/**全电pdf发票
 * Class InvoiceQdOcr
 * @package app\Ocr
 */
class InvoiceQdOcr extends BaseOcr
{

  static $request_url = "";
  static $request_url_pdf = "https://vatinvoice.market.alicloudapi.com/ai_market/ocr/digital_invoice/qd/pdf/v1";
  static $request_url_odf = "https://vatinvoice.market.alicloudapi.com/ai_market/ocr/digital_invoice/qdp/ofd/v1";
  static function getUrl($dirname,$file){
    $file_name = str_replace('|', '', $file);
    $info = pathinfo($file_name);
    $extension = $info['extension'] ?? "";
    $ip = get_image_ip_addr();
    if($extension  == 'ofd'){
      self::$request_url = self::$request_url_odf;
    }elseif ($extension == 'xml'){
      self::$request_url = "xml";
    }else{
      self::$request_url = self::$request_url_pdf;
    }
    return "$ip/$dirname/$file_name";
  }
  //进项票流程
  static function request($save_name){
    $save_name = str_replace(".PDF",'.pdf',$save_name);
    $options = [
      'form_params' => [
        'URL' => $save_name,
      ]
    ];
    if(self::$request_url == 'xml'){
      $data = file_get_contents($save_name);
      $body = new SimpleXMLElement($data);
      return InvoiceQdXml::parseByXML($body);
    }else{
      $body = self::getRequest($options);
      return self::parse($body);
    }
  }



  static $is_build;
  static function getGoodsType($goods){
    $title_list = array_flip($goods[0]??[]);
    $build_mark = $title_list["建筑服务发生地"]??'';
    $build_mark2 = $title_list["建筑项目名称"]??'';
    self::$is_build = ($build_mark||$build_mark2);
    if(self::$is_build){
      unset($goods[0]);
    }
    return $goods;
  }

  static function parse($response){
    $json = json_decode($response,true);
    $object = $json['电子发票（全电票）实体信息']??[];
    
    $sale = $object['销售方信息']??[];
    $buyer = $object['购买方信息']??[];
    $goods_list = $object['项目实体信息']??[];
    $invoice_type = $object['发票类型']??"增值税普票发票";

    $invoice_list = [];
    $tax_rate = "";
    $goods = self::getGoodsType($goods_list);
    $is_build = self::$is_build;

    foreach ($goods as $key=>$item){
      $tax_rate = self::replaceTaxRate($item['税率征收率']??null);
      $invoice_list[] = [
        'row_num'=>$key,
        'content'=>$is_build?(
          ($item['数量']??null).($item['单价']??null)
         ):($item['项目名称']??null),
        'sku'=>$is_build?null:($item['规格型号']??null),
        'unit'=>$is_build?null:($item['单位']??null),
        'num'=>$is_build?1:(float)($item['数量']??1),
        'price'=>(float)($item['单价']??null),
        'amount'=>(float)($item['金额']??0)+(float)($item['税额']??0),
        'tax_rate'=>$tax_rate,
        'tax_money'=>(float)($item['税额']??0),
        'not_tax_money'=>(float)($item['金额']??0),
        'project_address'=>$item['建筑服务发生地']??null,
        'project_name'=>$item['建筑项目名称']??null,
      ];
    }
    
    $data = [
      'supplier_name'=>$sale['名称']??null,
      'seller_info'=>[
        'name'=>$sale['名称']??null,
        'tax_no'=>$sale['统一社会用代码纳税人识别号']??null,
        'bank'=>null,
        'address'=>null,
        'tax_rate'=>$tax_rate??null,
      ],
      'amount_all'=>str_replace('￥','', $object['价税合计（小写）']??0),
      'not_tax_money_all'=>str_replace('￥','', $object['合计（金额）']??0),
      'tax_money_all'=>str_replace('￥','', $object['合计（税额）']??0),
      'invoice_date'=>self::replaceInvoiceDate($object['开票日期']??""),
      'purchase_name'=>$buyer['名称']??null,
      'purchase_info'=>[
        'name'=>$buyer['名称']??null,
        'tax_no'=>$buyer['统一社会用代码纳税人识别号']??null,
        'bank'=>null,
        'address'=>null,
      ],
      'invoice_order_no'=>$object['发票号码']??null,
      'code'=>$object['发票号码']??null,
      'invoice_type'=>strstr($invoice_type,'专')?1:2,
      'invoice_org'=>null,
      'machine_code'=>null,
      'check_code'=>null,
      'invoice_list' =>$invoice_list
    ];
    return $data;
  }

  //发票开具流程
  static function requestPdfByFinance($save_name){
    $options = [
      'form_params' => [
        'URL' => $save_name,
      ]
    ];
    self::$request_url = self::$request_url_pdf;
    $body = self::getRequest($options);
    return self::parsePdfByFinance($body);
  }

  static function parsePdfByFinance($response){
    $json = json_decode($response,true);
    $object = $json['电子发票（全电票）实体信息']??[];
    $sale = $object['销售方信息']??[];
    $buyer = $object['购买方信息']??[];
    $goods = $object['项目实体信息']??[];

    $goods = self::getGoodsType($goods);
    $is_build = self::$is_build;
    
    $first_good = [];
    $tax_rate = 0.01;
    foreach ($goods as $item){
      $rate = (int)$item['税率征收率']??"";
      if($rate){
        $first_good = $item;
        $tax_rate = self::replaceTaxRate($rate);
      }
    }
    $invoice_type = $object['发票类型']??"增值税普票发票";
    $is_special = strstr($invoice_type,'专票')?:strstr($invoice_type,'专用发票');
    $data = [
      'code'=>$object['发票号码']??null,
      'invoice_date'=>self::replaceInvoiceDate($object['开票日期']??""),
      'order_no'=>$object['发票号码']??"",
      'invoice_type'=>$is_special?1:2,
      'tax_rate'=>self::replaceTaxRate($tax_rate),
      'content'=>$is_build?(
        ($first_good['数量']??null).($first_good['单价']??null)
      ):($first_good['项目名称']??null),
      'sku'=>$is_build?null:($first_good['规格型号']??null),
      'unit'=>$is_build?null:($first_good['单位']??null),
      'num'=>$is_build?1:(float)($first_good['数量']??1),
      'amount'=>$object['价税合计（小写）']??"",
      'not_tax_money'=>$object['合计（金额）']??"",
      'tax_money'=>$object['合计（税额）']??"",
    ];
    return $data;
  }
  

}